import { menu } from '../../../app/decorator';
const { ccclass, property, requireComponent, playOnFocus, executionOrder, executeInEditMode, disallowMultiple } = cc._decorator;

@ccclass
@menu(__filename, '遮罩')
@playOnFocus
@executeInEditMode
@disallowMultiple
@executionOrder(1)
@requireComponent(cc.Mask)
export default class ColorShapMask extends cc.Component {
    @property({ tooltip: '反向遮罩' })
    inverted = true;
    @property({ tooltip: 'inverted属性是否影响touch' })
    invertTouch = true;

    protected onLoad() {
        const mask = this.getComponent(cc.Mask);
        const graphics = this.getComponent('BaseColorShap');
        if (!graphics) return;
        graphics._graphics && graphics._graphics.node.destroy();
        graphics._graphics = mask['_graphics'];
        graphics.updateColorShap();

        mask['_hitTest'] = this._hitTest.bind(this);
        mask['_updateGraphics'] = this._updateGraphics.bind(this);
    }

    protected onDestroy() {
        const graphics = this.getComponent('BaseColorShap');
        graphics && (graphics._graphics = null);
    }

    private _updateGraphics() {
        const graphics = this.getComponent('BaseColorShap');
        graphics && graphics.updateColorShap();
    }

    private _hitTest(...args: any[]) {
        let result = cc.Mask.prototype['_hitTest'].apply(this.getComponent(cc.Mask), args);
        if (this.inverted && !this.invertTouch) {
            result = !result;
        }
        return result;
    }
}
